package com.zh.note.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.note.annotation.MyRedisCache;
import com.zh.note.dao.UserMapper;
import com.zh.note.entity.UserEntity;
import com.zh.note.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author zhanghuan
 * @since 2024-09-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    private static final String CACHE_KEY_USER = "user:";

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<UserEntity> getUsers() {

        List<UserEntity> users = userMapper.getUsers();
        return users;
    }

//    @Override
//    public UserEntity getUserById(Integer id) {
//        UserEntity user = null;
//        //1.拼装 key
//        String key = CACHE_KEY_USER + id;
//        //2.从redis中查询数据
//        user = (UserEntity) redisTemplate.opsForValue().get(key);
//        if (user == null) {
//            // 3.redis中没有，则从mysql中查询
//            user = userMapper.getUserById(id);
//            if (user != null) {
//                //4.mysql查询成功，则缓存到redis中, 方便下次查询命中
//                redisTemplate.opsForValue().set(key, user);
//            }
//        }
//        return user;
//    }

    @Override
    public int addUser(UserEntity user) {
        //1 先往mysql插入数据库
        int retValue = userMapper.insert(user);
        if (retValue > 0) {
            //2 插入成功后，再查询数据库，并缓存到redis中
            user = this.userMapper.selectById(user.getUserId());
            String key = CACHE_KEY_USER + user.getUserId();
            redisTemplate.opsForValue().set(key, user);
        }
        return retValue;
    }

    /**
     * 会将返回值存进redis里，key生成规则需要程序员用SpEL表达式自己指定，value就是程序从mysql查出并返回的user
     * redis的key 等于  keyPrefix:matchValue
     */
    @Override
    @MyRedisCache(keyPrefix = "user", matchValue = "#id")
    public UserEntity getUserById(Integer id) {
        return userMapper.selectById(id);
    }
}
